package com.wl.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wl.entity.Dept;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/json")
public class JsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置相应的内容
        resp.setContentType("application/json;charset=utf-8");
        // 2. 设置相应出去的字符编码
        resp.setCharacterEncoding("utf-8");
        // 3. 得到输出流
        PrintWriter out = resp.getWriter();

        // java对象
        Dept d = new Dept(10,"a","aa");
        // java对象转json字符串
        String s = JSONObject.toJSONString(d);

        List<Dept> list = new ArrayList<>();
        list.add(new Dept(20,"b","bb"));
        list.add(new Dept(30,"c","bb"));
        list.add(new Dept(40,"d","bb"));
        list.add(new Dept(50,"e","bb"));
        // 集合转json数组字符串
        String s1 = JSONArray.toJSONString(list);

//        out.write(s);
        out.write(s1);
        // 5. 刷新
        out.flush();
    }
}
